package com.tron.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Scanner;

public class SocketStart {
    public static void main(String[] args) throws IOException {
        connectBaiDu();
    }

    public static void connectBaiDu() throws IOException {
        final Socket socket = new Socket();
        socket.connect(new InetSocketAddress("127.0.0.1", 9999), 3000);
        if (socket.isConnected()) {

            try (final InputStream inputStream = socket.getInputStream();
                 final OutputStream outputStream = socket.getOutputStream();
            ) {

                final Scanner s = new Scanner(inputStream);
                final PrintWriter printWriter = new PrintWriter(outputStream, true);
                final Scanner scanner = new Scanner(System.in);
                boolean done = false;


                while (!done) {
                    // 接收服务器返回信息
                    if (s.hasNext()) {
                        System.out.println(s.nextLine());
                    }

                    System.out.println("请回复服务器，如果不想聊了回复quit");
                    if (scanner.hasNextLine()) {
                        final String line = scanner.nextLine();
                        if (line.trim().equals("quit")) {
                            done = true;
                        }
                        // 向服务端写内容
                        printWriter.println(line);
                    }
                }
            }


        }
    }
}
